package ui;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.Random;

import javax.swing.AbstractAction;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.JWindow;
import javax.swing.LayoutStyle;
import javax.swing.SwingConstants;

import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;

import dao.ConnectionManager;
import dao.CreateTables;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class mainWindow extends javax.swing.JFrame {
	private boolean connected = false;
	private String[] statusStr = new String[] { "Status: Connected", "Status: Disconnected" };
	private String BD_NAME = "badass1";
	private JPanel jPanel1;
	private JMenuBar menuFile;
	private JMenu menuHelp;
	private JMenuItem updateActionMenu;
	private JLabel textHelp;
	private JDialog aboutDialog;
	private JMenuItem exitFileMenu;
	private JMenuItem aboutHelpMenu;
	private JMenuItem removeActionMenu;
	private AbstractAction connectionRetry;
	private AbstractAction tryConnectAction;
	private JMenuItem connect;
	private JMenu dbMenu;
	private JLabel statusNotifier;
	private JLabel derbyStatus;
	private JSeparator jSeparator1;
	private AbstractAction callRemoveForm;
	private AbstractAction callSearchForm;
	private AbstractAction callUpdateForm;
	private AbstractAction exitAct;
	private AbstractAction callInsertForm;
	private AbstractAction jActionInsCancel;
	private AbstractAction OK_insert;
	private AbstractAction callAboutDialog;
	private AbstractAction closeAboutBt;
	private JButton okAboutBt;
	private JMenuItem searchActionMenu;
	private JMenuItem insertActionMenu;
	private JMenu actionMenu;
	private JMenu jMenu1;
	/* Useful stuff, don't touch... */
    public static final String[]
    RiskOfExtinction = {"Extinct",
                        "Extinct in the Wild",
                        "Critically Endangered",
                        "Endangered",
                        "Vulnerable",
                        "Near Threatened",
                        "Least Concern"};

	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				mainWindow inst = new mainWindow();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public mainWindow() {
		super();
		initGUI();
	}
	
	private void initGUI() {
		/* Start up the database */
        estabilishConnection();
        
		try {
			GroupLayout thisLayout = new GroupLayout((JComponent)getContentPane());
			getContentPane().setLayout(thisLayout);
			thisLayout.setHorizontalGroup(thisLayout.createSequentialGroup()
				.addComponent(getJPanel1(), GroupLayout.PREFERRED_SIZE, 394, GroupLayout.PREFERRED_SIZE));
			thisLayout.setVerticalGroup(thisLayout.createSequentialGroup()
				.addContainerGap(222, 222)
				.addComponent(getJPanel1(), GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE));
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			this.setResizable(false);
			this.setVisible(false);
			this.setTitle("Ave na Mata");
			{
				menuFile = new JMenuBar();
				setJMenuBar(menuFile);
				{
					jMenu1 = new JMenu();
					menuFile.add(jMenu1);
					jMenu1.setText("File");
					{
						exitFileMenu = new JMenuItem();
						jMenu1.add(exitFileMenu);
						exitFileMenu.setText("Exit");
						exitFileMenu.setAction(getExitAct());
					}
				}
				{
					actionMenu = new JMenu();
					menuFile.add(actionMenu);
					menuFile.add(getDbMenu());
					actionMenu.setText("Action");
					{
						insertActionMenu = new JMenuItem();
						actionMenu.add(insertActionMenu);
						insertActionMenu.setText("Insert");
						insertActionMenu.setAction(getCallInsertForm());
					}
					{
						updateActionMenu = new JMenuItem();
						actionMenu.add(updateActionMenu);
						updateActionMenu.setText("Update");
						updateActionMenu.setAction(getCallUpdateForm());
					}
					{
						searchActionMenu = new JMenuItem();
						actionMenu.add(searchActionMenu);
						searchActionMenu.setText("Search");
						searchActionMenu.setAction(getCallSearchForm());
					}
					{
						removeActionMenu = new JMenuItem();
						actionMenu.add(removeActionMenu);
						removeActionMenu.setText("Remove");
						removeActionMenu.setAction(getCallRemoveForm());
					}
				}
				{
					menuHelp = new JMenu();
					menuFile.add(menuHelp);
					menuHelp.setText("Help");
					{
						aboutHelpMenu = new JMenuItem();
						menuHelp.add(aboutHelpMenu);
						aboutHelpMenu.setText("About");
						aboutHelpMenu.setAction(getCallAboutDialog());
					}
				}
			}
			pack();
			setSize(400, 300);
		} catch (Exception e) {
		    //add your error handling code here
			e.printStackTrace();
		}
	}
	
	private JDialog getAboutDialog() {
		if(aboutDialog == null) {
			aboutDialog = new JDialog(this);
			GroupLayout aboutDialogLayout = new GroupLayout((JComponent)aboutDialog.getContentPane());
			aboutDialog.getContentPane().setLayout(aboutDialogLayout);
			aboutDialog.setPreferredSize(new java.awt.Dimension(353, 211));
			aboutDialog.setSize(353, 211);
			aboutDialogLayout.setHorizontalGroup(aboutDialogLayout.createSequentialGroup()
				.addContainerGap(94, 94)
				.addGroup(aboutDialogLayout.createParallelGroup()
				    .addComponent(getTextHelp(), GroupLayout.Alignment.LEADING, 0, 191, Short.MAX_VALUE)
				    .addGroup(GroupLayout.Alignment.LEADING, aboutDialogLayout.createSequentialGroup()
				        .addGap(50)
				        .addComponent(getOkAboutBt(), 0, 53, Short.MAX_VALUE)
				        .addGap(88)))
				.addContainerGap(52, 52));
			aboutDialogLayout.setVerticalGroup(aboutDialogLayout.createSequentialGroup()
				.addContainerGap()
				.addComponent(getTextHelp(), 0, 121, Short.MAX_VALUE)
				.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
				.addComponent(getOkAboutBt(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				.addContainerGap());
		}
		return aboutDialog;
	}
	
	private JLabel getTextHelp() {
		if(textHelp == null) {
			textHelp = new JLabel();
			textHelp.setText("Versão inicial do programa...");
			textHelp.setHorizontalTextPosition(SwingConstants.CENTER);
		}
		return textHelp;
	}
	
	private JButton getOkAboutBt() {
		if(okAboutBt == null) {
			okAboutBt = new JButton();
			okAboutBt.setText("Ok");
			okAboutBt.setAction(getCloseAboutBt());
		}
		return okAboutBt;
	}
	
	private AbstractAction getCloseAboutBt() {
		if(closeAboutBt == null) {
			closeAboutBt = new AbstractAction("Ok", null) {
				public void actionPerformed(ActionEvent evt) {
					getAboutDialog().dispose();
				}
			};
		}
		return closeAboutBt;
	}
	
	private AbstractAction getCallAboutDialog() {
		if(callAboutDialog == null) {
			callAboutDialog = new AbstractAction("About", null) {
				public void actionPerformed(ActionEvent evt) {
					getAboutDialog().pack();
					getAboutDialog().setLocationRelativeTo(null);
					getAboutDialog().setVisible(true);
				}
			};
		}
		return callAboutDialog;
	}
	
	private AbstractAction getCallInsertForm() {
		if(callInsertForm == null) {
			callInsertForm = new AbstractAction("Insert", null) {
				public void actionPerformed(ActionEvent evt) {
					insertWindow inst = new insertWindow();
					inst.setLocationRelativeTo(null);
					inst.setVisible(true);
				}
			};
		}
		return callInsertForm;
	}
	
	private AbstractAction getExitAct() {
		if(exitAct == null) {
			exitAct = new AbstractAction("Exit", null) {
				public void actionPerformed(ActionEvent evt) {
					try {
						ConnectionManager.disconnect();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mainWindow.this.dispose();
				}
			};
		}
		return exitAct;
	}
	
	private AbstractAction getCallUpdateForm() {
		if(callUpdateForm == null) {
			callUpdateForm = new AbstractAction("Update", null) {
				public void actionPerformed(ActionEvent evt) {
					updateWindow inst = new updateWindow();
					inst.setLocationRelativeTo(null);
					inst.setVisible(true);
				}
			};
		}
		return callUpdateForm;
	}
	
	private AbstractAction getCallSearchForm() {
		if(callSearchForm == null) {
			callSearchForm = new AbstractAction("Search", null) {
				public void actionPerformed(ActionEvent evt) {
					searchWindow inst = new searchWindow();
					inst.setLocationRelativeTo(null);
					inst.setVisible(true);
				}
			};
		}
		return callSearchForm;
	}
	
	private AbstractAction getCallRemoveForm() {
		if(callRemoveForm == null) {
			callRemoveForm = new AbstractAction("Remove", null) {
				public void actionPerformed(ActionEvent evt) {
					removeWindow inst = new removeWindow();
					inst.setLocationRelativeTo(null);
					inst.setVisible(true);
				}
			};
		}
		return callRemoveForm;
	}
	
	private JSeparator getJSeparator1() {
		if(jSeparator1 == null) {
			jSeparator1 = new JSeparator();
		}
		{
			derbyStatus = new JLabel();
			derbyStatus.setText("Status: Connected");
			derbyStatus.setPreferredSize(new java.awt.Dimension(0, 0));
		}
		return jSeparator1;
	}
	
	private JPanel getJPanel1() {
		if(jPanel1 == null) {
			jPanel1 = new JPanel();
			GroupLayout jPanel1Layout = new GroupLayout((JComponent)jPanel1);
			jPanel1.setLayout(jPanel1Layout);
			{
				jSeparator1 = new JSeparator();
			}
			jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup()
				.addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
				    .addComponent(getStatusNotifier(), GroupLayout.PREFERRED_SIZE, 124, GroupLayout.PREFERRED_SIZE)
				    .addGap(0, 270, Short.MAX_VALUE))
				.addComponent(getJSeparator1(), GroupLayout.Alignment.LEADING, 0, 394, Short.MAX_VALUE));
			jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup()
				.addComponent(getStatusNotifier(), GroupLayout.Alignment.LEADING, 0, 23, Short.MAX_VALUE)
				.addGroup(GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
				    .addComponent(getJSeparator1(), GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)
				    .addGap(0, 21, Short.MAX_VALUE)));
		}
		return jPanel1;
	}
	
	
	private JLabel getStatusNotifier() {
		if(statusNotifier == null) {
			statusNotifier = new JLabel();
			statusNotifier.setText("Status: Connected");
		}
		return statusNotifier;
	}
	
	private JMenu getDbMenu() {
		if(dbMenu == null) {
			dbMenu = new JMenu();
			dbMenu.setText("Database");
			dbMenu.add(getConnect());
		}
		return dbMenu;
	}
	
	private JMenuItem getConnect() {
		if(connect == null) {
			connect = new JMenuItem();
			connect.setText("Connect");
			connect.setAction(getConnectionRetry());
		}
		return connect;
	}
	
	private AbstractAction getTryConnectAction() {
		if(tryConnectAction == null) {
			tryConnectAction = new AbstractAction("Connect", null) {
				public void actionPerformed(ActionEvent evt) {
					
				}
			};
		}
		return tryConnectAction;
	}
	
	//Try to connect to the database.
	private void estabilishConnection() {
		try {
			CreateTables.Create(BD_NAME);
            ConnectionManager.connect(BD_NAME);
            System.out.println("Conected!");
            connected = true;
        } catch(SQLException ex) {
            System.out.println("Connection failed!");
            System.out.println(ex.getMessage());
            System.out.println(ex.getNextException().getMessage());
        } catch(Exception e) {
        	System.out.println(e.getMessage());
        } 
        
        updateStatus();
	}
	
	// Update teh status bar with the currently connection status.
	private void updateStatus() {
		
		if ( connected ) {
        	getStatusNotifier().setText(statusStr[0]);
        	getConnect().setText("Connected");
        	getConnect().setEnabled(false);
        } else {
        	getStatusNotifier().setText(statusStr[1]);
        	getConnect().setEnabled(true);
        	getConnect().setText("Connect");
        }
		
	}
	
	//This method retries 10 times to estabilsh connection
	//to the database.
	private AbstractAction getConnectionRetry() {
		if(connectionRetry == null) {
			connectionRetry = new AbstractAction("cAct", null) {
				public void actionPerformed(ActionEvent evt) {
					int i, maxTry = 10;
					
					for ( i = 0; i < maxTry; i++ ) {
						estabilishConnection();
					}
				}
			};
		}
		return connectionRetry;
	}

}
